﻿using B.MESUI.Login.WareHouseManage;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static B.MESUI.Login.WareHouseManage.UpdateWareHouseDefinitionForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace B.MESUI.Login
{
    public partial class WareHouseDefinitionForm : DevExpress.XtraEditors.XtraForm
    {
        public WareHouseDefinitionForm()
        {
            InitializeComponent();
            this.Load += WareHouseDefinitionForm_Load;

        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            CreateWareHouseDefinitionForm createWareHouseDefinition = new CreateWareHouseDefinitionForm();
            createWareHouseDefinition.ShowDialog();
            
        }

        private async void WareHouseDefinitionForm_Load(object sender, EventArgs e)
        {
            LoadWareHouseDefinitionList(1, 10);


            // 获取 GridView
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;

            // 假设 gridView1 是 gridControl1 的主视图
            gridView.OptionsSelection.MultiSelect = true;
            gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            gridView.OptionsSelection.ShowCheckBoxSelectorInGroupRow = DevExpress.Utils.DefaultBoolean.True;
        }
        public async Task LoadWareHouseDefinitionList(int pageIndex, int pageSize)
        {
            //string apiUrl = "http://localhost:5031/api/WareHouseDefinition/GetWAREHOUSEDEFINITIONMODEL?PageIndex=" + pageIndex + "&PageSize=" + pageSize;
            string apiUrl = "http://39.103.49.30:9981/api/WareHouseDefinition/GetWAREHOUSEDEFINITIONMODEL?PageIndex=" + pageIndex + "&PageSize=" + pageSize;
            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<WareHouseDefinitionApiResult>(json);
                    if (result != null && result.PageDatas != null)
                    {
                        gridControl1.DataSource = result.PageDatas;
                    }
                }
                else
                {
                    MessageBox.Show("获取数据失败！");
                }
            }
        }

        public class WareHouseDefinitionApiResult
        {
            public List<WareHouseDefinitionModel> PageDatas { get; set; }
            public int Total { get; set; }
        }

        public class WareHouseDefinitionModel
        {
            public string ID { get; set; }
            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public DateTime CREATETIME { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSEDEFINITIONCODE { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSENAME { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSETYPE { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSEMANAGER { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSEADDRESS { get; set; }

            /// <summary>
            /// Desc:
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string WAREHOUSEADDRESSDESC { get; set; }
        }
        private async void simpleButton3_Click(object sender, EventArgs e)
        {
            // 获取所有选中的行
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                MessageBox.Show("请选择要删除的信息！");
                return;
            }

            // 确认删除
            if (MessageBox.Show("确定要删除选中的信息吗？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            foreach (var rowHandle in selectedRows)
            {
                var rowData = gridView1.GetRow(rowHandle) as WareHouseDefinitionModel;
                if (rowData != null)
                {
                    // 假设后端API为 DELETE http://localhost:5031/api/WareHouseDefinition/Delete/{id}
                    string apiUrl = $"http://39.103.49.30:9981/api/WareHouseDefinition/DeleteWAREHOUSEDEFINITIONMODEL?id={rowData.ID}";
                    using (HttpClient client = new HttpClient())
                    {
                        var emptyContent = new StringContent("", Encoding.UTF8, "application/json");
                        var response = await client.PostAsync(apiUrl, emptyContent);
                        if (!response.IsSuccessStatusCode)
                        {
                            MessageBox.Show($"删除ID为{rowData.ID}的数据失败！");
                        }
                    }
                }
            }

            // 删除后刷新列表
            await LoadWareHouseDefinitionList(1, 10);
        }

        private async void simpleButton4_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();

            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("还没有选中要编辑的数据");
                return;
            }

            if (selectedRows.Length > 1)
            {
                XtraMessageBox.Show("无法一次编辑多条数据");
                return;
            }

            // 只选中了一行，开始编辑
            var rowData = gridView1.GetRow(selectedRows[0]) as WareHouseDefinitionModel;
            if (rowData == null)
            {
                XtraMessageBox.Show("获取数据失败");
                return;
            }

            string apiUrl = $"http://39.103.49.30:9981/api/WareHouseDefinition/GetWAREHOUSEDEFINITIONDESC?id={rowData.ID}";

            using (var client = new HttpClient())
            {
                var response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // 解析包含 ResultData 的响应
                    var resultWrapper = JsonConvert.DeserializeObject<ApiResult<WareHouseDefinitionEditModel>>(json);

                    if (resultWrapper != null && resultWrapper.ResultData != null)
                    {
                        var editModel = resultWrapper.ResultData;

                        // 打开编辑窗口并传入数据
                        var editForm = new UpdateWareHouseDefinitionForm();
                        editForm.SetEditData(editModel);

                        if (editForm.ShowDialog() == DialogResult.OK)
                        {
                            // 刷新列表
                            await LoadWareHouseDefinitionList(1, 10);
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取的数据格式不正确");
                    }
                }
                else
                {
                    XtraMessageBox.Show("获取编辑数据失败");
                }
            }
        }
        /// <summary>
        /// 泛型 API 返回结果封装类
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        public class ApiResult<T>
        {
            public string Code { get; set; }      // 状态码
            public string Message { get; set; }   // 返回消息
            public T ResultData { get; set; }     // 实际返回的数据
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 收集查询条件
                string warehouseCode = this.textEdit1.Text.Trim();
                string warehouseName = this.textEdit2.Text.Trim();
                string warehouseType = this.textEdit3.Text.Trim();
                string warehouseManager = this.textEdit4.Text.Trim();
                string warehouseAddress = this.textEdit5.Text.Trim();

                // 构建查询URL
                string apiUrl = "http://39.103.49.30:9981/api/WareHouseDefinition/GetWAREHOUSEDEFINITIONMODEL?";

                // 添加分页参数
                apiUrl += "PageIndex=1&PageSize=10";

                // 添加查询条件参数（不为空时才添加）
                if (!string.IsNullOrWhiteSpace(warehouseCode))
                    apiUrl += $"&WAREHOUSEDEFINITIONCODE={Uri.EscapeDataString(warehouseCode)}";

                if (!string.IsNullOrWhiteSpace(warehouseName))
                    apiUrl += $"&WAREHOUSENAME={Uri.EscapeDataString(warehouseName)}";

                if (!string.IsNullOrWhiteSpace(warehouseType))
                    apiUrl += $"&WAREHOUSETYPE={Uri.EscapeDataString(warehouseType)}";

                if (!string.IsNullOrWhiteSpace(warehouseManager))
                    apiUrl += $"&WAREHOUSEMANAGER={Uri.EscapeDataString(warehouseManager)}";

                if (!string.IsNullOrWhiteSpace(warehouseAddress))
                    apiUrl += $"&WAREHOUSEADDRESS={Uri.EscapeDataString(warehouseAddress)}";

                // 调用API获取数据
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<WareHouseDefinitionApiResult>(json);

                        if (result != null && result.PageDatas != null)
                        {
                            gridControl1.DataSource = result.PageDatas;
                            XtraMessageBox.Show($"查询到 {result.PageDatas.Count} 条记录");
                        }
                        else
                        {
                            gridControl1.DataSource = null;
                            XtraMessageBox.Show("未查询到匹配的记录");
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show($"查询失败: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询发生异常: {ex.Message}");
            }
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            this.textEdit1.Text = "";
            this.textEdit2.Text = "";
            this.textEdit3.Text = "";
            this.textEdit4.Text = "";
            this.textEdit5.Text = "";
        }
    }
}